package jwdt.xadmin.custom.service.impl;


import java.util.List;

import jwdt.common.dao.BaseDao;
import jwdt.xadmin.custom.bean.TContacts;
import jwdt.xadmin.custom.bean.TCustom;
import jwdt.xadmin.custom.service.CustomManageService;

import com.ezerg.db.Jdb;
import com.ezerg.db.ext.PageUtil;
import com.ezerg.fastjson.JSON;
import com.ezerg.util.DateUtil;
import com.ezerg.util.StringUtil;
public class CustomManageServiceImpl implements CustomManageService{
	private BaseDao<TCustom> baseDao;
	
	public void setBaseDao(BaseDao<TCustom> baseDao) {
		this.baseDao = baseDao;
	}
	
	@Override
	public PageUtil doList(PageUtil pu, TCustom tc ,int userid) throws Exception{
		String where = "";
		String name = tc.getName();
		if(!StringUtil.nullOrBlank(name)) {
			where += " name like '%" + name + "%'";
		}
		where += " owner=" + userid;
		String sql = " order by logdt desc";
		pu.doList(TCustom.class,where+sql);
		//创造json数据对象
		return pu;
	}
	
	@Override
	public PageUtil doList(PageUtil pu, TCustom tc) throws Exception{
		String where = "";
		String name = tc.getName();
		if(!StringUtil.nullOrBlank(name)) {
			where += " name like '%" + name + "%'";
		}
		Integer owner = tc.getOwner();
		if(owner != null && owner != 0) {
			where += " owner=" + owner;
		}
		String sql = " order by logdt desc";
		pu.doList(TCustom.class,where+sql);
		//创造json数据对象
		return pu;
	}
	
	@Override
	public String doAddact(TCustom obj,String contact) throws Exception {
		String dt = DateUtil.getDateTime();
		obj.setDt(dt);
		String ret = baseDao.doAddObj(obj);
		try {
			List<TContacts> list = JSON.parseArray(contact, TContacts.class);
			int customId = TCustom.getIdByDt(dt);
			for (TContacts tContacts : list) {
				String d = System.currentTimeMillis()+"";
				tContacts.setDt(d);
				Jdb.get().add(tContacts);
				int id = TContacts.getIdByDt(d);
				TCustom.insertCascade(customId, id);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	@Override
	public String doEditact(TCustom obj, int id,String contact) throws Exception {
		String ret = baseDao.doUpdateObj(TCustom.class, id, obj);
		try {
			List<TContacts> list = JSON.parseArray(contact, TContacts.class);
			for (TContacts tContacts : list) {
				Integer contactId = tContacts.getId();
				if(contactId!=null && contactId!=0){
					Jdb.get().update(tContacts);
				}else{
					String d = System.currentTimeMillis()+"";
					tContacts.setDt(d);
					Jdb.get().add(tContacts);
					contactId = TContacts.getIdByDt(d);
					TCustom.insertCascade(id, contactId);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	};
	
	@Override
	public String doDelact(int id) throws Exception {
		TCustom.deleteCascade(id);
		return baseDao.doDelObj(TCustom.class, id);
	}

	@Override
	public TCustom doLoad(int id) throws Exception {
		return baseDao.doLoadObj(TCustom.class, id);
	}
}
